from flask import json
g_filter_route = dict()

def upd_filter(filt_name):
    def func1(func):
        g_filter_route[filt_name] = func
        
        def func2(recv_data, que_dict):
            return func(recv_data, que_dict)
        
        return func2
    
    return func1


# 检验是否为json数据
@upd_filter("json")
def is_json(recv_data, que_dict):
    json_data = que_dict.get("json_data")
    is_json = False
    try:
        json_data = json.loads(recv_data[0].decode("utf-8"))
        if json_data is not None:
            is_json = True
            que_dict["json_data"] = json_data
    except Exception as e:
        is_json = False
    return is_json


def is_recv_core(json_data, keys):
    return 1 if json_data.get(keys) else 0


# 检验接受数据是否符合格式
@upd_filter("is_recv")
def is_recv(recv_data, que_dict):
    json_data = que_dict.get("json_data")
    if json_data:
        recv_list = [
            is_recv_core(json_data, "server_ip"),
            is_recv_core(json_data, "server_port")
        ]
        return sum(recv_list) == (len(recv_list))
    return False